<template>
  <div>
    <!-- 标题 -->
    <el-collapse class="top">
      <el-collapse-item title="商品管理介绍" class="top-title">
        <div class="top-div">
          商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情
        </div>
      </el-collapse-item>
    </el-collapse>
  <!-- 条件查询 -->
    <el-collapse>
      <el-collapse-item title="条件查询" class="top-title">
        <el-form
          :model="formList"
          label-width="120px"
          :inline="false"
          size="normal"
        >
          <el-row :gutter="20">
            <el-col :span="6"
              ><el-form-item label="商品名称">
                <el-input
                  placeholder="请输入搜索名称"
                  v-model="formList.name"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="6"
              ><el-form-item label="商品货号">
                <el-input
                  placeholder="请输入搜索货号"
                  v-model="formList.productSn"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="6"
              ><el-form-item label="品牌">
                <el-select v-model="formList.brandId" placeholder="请选择">
                  <el-option
                    v-for="item in searchList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>

            <el-col :span="6"
              ><el-form-item label="上架状态">
                <el-select
                  v-model="formList.publishStatus"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in upStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="审核状态">
                <el-select v-model="formList.verifyStatus" placeholder="请选择">
                  <el-option
                    v-for="item in auditStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" :offset="12">
              <el-form-item>
                <el-button type="primary" @click="immSearch"
                  >立即搜索</el-button
                >
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
    </el-collapse>
  <!-- 页面展示 -->
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin-top: 30px"
    >
      <el-button style="margin-bottom:20px" type="primary" size="default" @click="addNewShop">新增商品</el-button>
      
      <el-table :data="tableList" border style="width: 100%">
        <el-table-column type="index" label="#" align="center">
        </el-table-column>

        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <div class="img">
              <img :src="scope.row.pic" alt="" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.name }}</div>
            <div>品牌：{{ scope.row.brandName }}</div>
            <div>{{ scope.row.description }}</div>
          </template>
        </el-table-column>

        <el-table-column label="商品价格" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.originalPrice }}</div>
            <div>{{ scope.row.price }}</div>
          </template>
        </el-table-column>

        <el-table-column
          prop="productCategoryName"
          label="商品类别"
          width="180"
          align="center"
        >
        </el-table-column>

        <el-table-column label="标签" align="center">
          <template slot-scope="scope">
            <div class="margin-bottom">
              最新:<el-switch
                v-model="scope.row.newStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeNewStatus(scope.row)"
              >
              </el-switch>
            </div>
            <div>
              推荐:<el-switch
                v-model="scope.row.recommendStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeRecommendStatus(scope.row)"
              >
              </el-switch>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="标签2" align="center">
          <template slot-scope="scope">
            <div class="margin-bottom">
              发布:<el-switch
                v-model="scope.row.publishStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeIssueStatus(scope.row)"
              >
              </el-switch>
            </div>
            <div>
              审核:<el-switch
                v-model="scope.row.verifyStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeVerifyStatus(scope.row)"
              >
              </el-switch>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="sku" align="center">
          <template slot-scope="scope" align="center">
            <el-button
              type="primary"
              size="default"
              @click="goEditSku(scope.row.id)"
              >编辑sku</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="重量" prop="weight" align="center">
        </el-table-column>

        <el-table-column label="排序" prop="sort" align="center">
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope" align="center">
            <el-button
              type="primary"
              size="mini"
              @click="editNowItem(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="delNowItem(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="start"
        :page-sizes="[5, 10]"
        :page-size="limit"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="fullData"
      >
      </el-pagination>
    </el-card>

    <!-- 编辑sku信息 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="90%">
      <!-- <el-form ref="form" :model="detailSkuList" label-width="120px"> -->
      <div class="addSku">
        <el-button type="primary" size="default" @click="addSkuMes"
          >新增sku信息</el-button
        >
      </div>
      <el-row :gutter="20">
        <el-col :span="22" :offset="2">
          <el-table :data="detailSkuList" border style="width: 100%">
            <el-table-column type="index" label="#" align="center">
            </el-table-column>
            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <el-upload
                  class="avatar-uploader"
                  action="/lejuAdmin/material/uploadFileOss"
                  ref="tableListImg"
                  :on-success="tableListImg"
                  :headers="{ token: fileToken }"
                >
                  <img
                    @click="pic(scope.$index)"
                    class="img"
                    v-if="scope.row.pic"
                    :src="scope.row.pic"
                  />
                  <i
                    @click="pic(scope.$index)"
                    v-else
                    style="height: 100px"
                    class="el-icon-plus avatar-uploader-icon"
                  ></i>
                </el-upload>
              </template>
            </el-table-column>

            <el-table-column label="颜色" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[0].value"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="大小" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[1].value"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="库存" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="预警库存" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="预警库存" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lockStock"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="sku编码" align="center">
              <template slot-scope="scope">
                <el-input
                  style="font-size: 12px"
                  placeholder="自定义sku编码"
                  v-model="scope.row.skuCode"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="销量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sale"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <div class="btn">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delTableSku(scope.row.id, scope.$index)"
                    >删除</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    v-if="scope.row.show"
                    @click="doSaveSkuList(scope.$index)"
                    >保存</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    v-else
                    @click="alterSave(scope.row)"
                    >修改编辑</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- </el-form> -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <buttomBanner></buttomBanner>
  </div>
</template>

<script>
import {
  productsByPage,
  findAllBrand,
  switchNewStatus,
  switchPublishStatus,
  switchRecommandStatus,
  switchVerifyStatus,
  del,
  getSkusByProductId,
  addProductSkus,
  delSku,
  updateSkuInfo
} from "@/api/product/productList/productList.js";
import buttomBanner from "@/components/buttomBanner";
import { getToken } from "@/utils/auth.js";
export default {
   name:"productList",
  data() {
   
    return {
      upStatus: [
        {
          value: 0,
          label: "未上架",
        },
        {
          value: 1,
          label: "已上架",
        },
      ],
      auditStatus: [
        {
          value: 0,
          label: "未审核",
        },
        {
          value: 1,
          label: "已审核",
        },
      ],
      searchList: [],
      formList: {},
      tableList: [],
      start: 1,
      limit: 5,
      fullData: 0,
      statusVo: {},
      detailSkuList: [],
      dialogVisible: false,
      skuId: "",
    };
  },
  computed: {
    // 上传图片携带token信息
    fileToken() {
      return getToken();
    },
  },
  components: {
    buttomBanner,
  },
  methods: {
    // 新增商品
    addNewShop(){
      this.editNowItem()
    },
    // 修改编辑保存
    alterSave(item){
      item.spData = JSON.stringify(item.spData)
      updateSkuInfo(item).then(res=>{
        if(res.success){
          this.$message.success("修改成功")
        }else{
          this.$message.error(res.message)
        }
      })
    },
    // 保存新增sku
    doSaveSkuList(index) {
      var skuStock = this.detailSkuList[index];
      delete skuStock.show;
      skuStock.spData = JSON.stringify(skuStock.spData);
      console.log(skuStock);
      addProductSkus(skuStock).then((res) => {
        if (res.success) {
          this.$message.success("保存成功");
          this.goEditSku(this.skuId);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 点击新增sku信息
    addSkuMes() {
      this.detailSkuList.push({
        lockStock: "",
        lowStock: "",
        pic: "",
        price: "",
        productId: this.skuId,
        sale: "",
        skuCode: "",
        stock: "",
        show: true,
        spData: [
          {
            key: "",
            value: "",
          },
          {
            key: "",
            value: "",
          },
        ],
      });
    },
    // upload点击传当前index
    pic(index) {
      this.index = index;
    },
    // sku列表中的img
    tableListImg(v) {
      if (v.success) {
        this.$refs.tableListImg.clearFiles();
        this.$set(this.detailSkuList[this.index], "pic", v.data.fileUrl);
      }
    },
    // 删除sku当前行
    delTableSku(id, index) {
      this.$confirm(
        "此操作删除当前sku行, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then((res) => {
          if (res == "confirm") {
            if (id) {
              delSku(id).then((res) => {
                if (res.success) {
                  this.$message.success("删除成功");
                  this.goEditSku(this.skuId);
                } else {
                  this.$message.error(res.message);
                }
              });
            } else {
              this.detailSkuList.splice(index,1)
            }
          }
        })
        .catch((res) => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 进入编辑sku信息
    goEditSku(id) {
      this.skuId = id;
      getSkusByProductId(id).then((res) => {
        if (res.success) {
          res.data.items.forEach((el) => {
            el.spData = JSON.parse(el.spData);
          });
          this.detailSkuList = res.data.items;
          this.dialogVisible = true;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 编辑当前行
    editNowItem(item) {
      if(item){
        window.localStorage.setItem("productId", item.id);
      }else{
        window.localStorage.setItem("productId", []);
      }
      this.$router.push({ name: "ProductEditProduct" });
    },
    // 删除当前项
    delNowItem(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          if (res == "confirm") {
            del(id).then((res) => {
              if (res.success) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.init();
              }
            });
          }
        })
        .catch((res) => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 更改是否最新状态
    changeNewStatus(item) {
      this.statusVo = {
        productId: item.id,
        status: item.newStatus,
      };
      switchNewStatus(this.statusVo).then((res) => {
        if (res.success) {
          this.$message.success("更改最新状态成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 更改是否发布状态
    changeIssueStatus(item) {
      this.statusVo = {
        productId: item.id,
        status: item.newStatus,
      };
      switchPublishStatus(this.statusVo).then((res) => {
        if (res.success) {
          this.$message.success("更改发布状态成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 更改是否推荐状态
    changeRecommendStatus(item) {
      this.statusVo = {
        productId: item.id,
        status: item.newStatus,
      };
      switchRecommandStatus(this.statusVo).then((res) => {
        if (res.success) {
          this.$message.success("更改推荐状态成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 更改审核状态
    changeVerifyStatus(item) {
      this.statusVo = {
        productId: item.id,
        status: item.newStatus,
      };
      switchVerifyStatus(this.statusVo).then((res) => {
        if (res.success) {
          this.$message.success("更改审核状态成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 立即搜索
    immSearch() {
      this.start = 1;
      this.limit = 5;
      this.init();
    },
    // 重置搜索关键词
    resetSearch() {
      this.formList = {};
      this.start = 1;
      this.limit = 5;
      this.init();
    },
    // 切换表格每页显示数量
    handleSizeChange(v) {
      this.limit = v;
      this.start = 1;
      this.init();
    },
    // 切换页码
    handleCurrentChange(v) {
      this.start = v;
      this.init();
    },
    init() {
      productsByPage(this.start, this.limit, this.formList).then((res) => {
        if (res.success) {
          this.tableList = res.data.rows;
          this.fullData = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 获取搜索列表品牌下拉框内容
    initSearchList() {
      var obj = {};
      var arr = [];
      findAllBrand().then((res) => {
        if (res.success) {
          res.data.items.forEach((el) => {
            obj.value = el.id;
            obj.label = el.name;
            arr.push(obj);
            obj = {};
          });
          this.searchList = arr;
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
  created() {
    this.init();
    this.initSearchList();
  },
};
</script>

<style lang="scss" scoped>
.top {
  margin-bottom: 30px;
}
.top-title {
  font-size: 20px !important;
  text-indent: 20px;
}
.top-div {
  padding: 0 20px;
  font-size: 16px;
}
.img {
  display: flex;
  img {
    width: 100px;
    height: 100px;
    margin: auto;
  }
}

.el-pagination {
  text-align: center;
  margin-top: 10px;
}
.margin-bottom {
  margin-bottom: 10px;
}
.img {
  width: 100px;
  height: auto;
  display: block;
  margin: auto;
}
.addSku {
  margin: 0px 0 20px 5px;
}
.btn {
  display: flex;
}
.el-row {
  display: flex;
  .el-col-offset-2 {
    margin: auto;
  }
}
</style>